<?php
	class Template
	{
		private $registry;
		private $vars = array();

		public function __construct($registry)
		{
			$this->registry = $registry;
		}

		public function __set($index, $value)
		{
			$this->vars[$index] = $value;
		}

		public function show($name, $sort = array(), $viewpath = null)
		{
			$this->render($name, $sort, $viewpath);
		}

		public function render($name, $sort = array(), $viewpath = null)
		{
			if($viewpath == null)
				$path = _ROOT . '/view/' . $name . '.php';
			else
				$path = _ROOT . $viewpath . '/view/' . $name . '.php';

			if(file_exists($path) == false)
			{
				throw new Exception("Template not found in " . $path);
				return false;				
			}

			foreach($this->vars as $key => $value)
			{
				$$key = $value;
			}

			if(count($sort) > 0 && in_array(CONTROLLER, $sort))
			{
				foreach($sort as $node)
				{
					if($node == CONTROLLER)
					{
						include $path;
					}
					else
					{
						$file =  _ROOT . '/templates/' . $this->registry->cfg->template . '/' . $node . '.php';
						if(file_exists($file))
						{
							include $file;
						}
						else
						{
							throw new Exception("Template part '" . $file . "' not found.");
							return false;	
						}
					}
				}
			}
			else
			{
				include $path;
			}
		}
	}
?>